import { useQuery } from '@tanstack/vue-query'
import { computed, toRef, type Ref } from 'vue'

import { ApiSearchUser, useSearchUserQueryKey } from '@/apis/user'
import { Role, roleIsEnabled } from '@/constants/role'
import { useUserStore } from '@/stores/user'

export type TeacherOption = Record<'value' | 'label', string>
export function useTeacher(visible: Ref<boolean>) {
  const user = toRef(useUserStore(), 'user')
  const notDisable = computed(() => visible.value && roleIsEnabled(user.value.role, Role.Admin))

  const { data: teachers, isLoading } = useQuery({
    enabled: notDisable,
    staleTime: 60_000,
    queryKey: useSearchUserQueryKey({ role: Role.Teacher }),
    queryFn: ({ queryKey: [, , query] }) => ApiSearchUser(query),
    select({ data }) {
      return data.map<TeacherOption>(({ username, name }) => ({
        value: username,
        label: name
      }))
    }
  })

  const teacherFilter = (input: string, { value, label }: TeacherOption) => {
    return `${value}${label}`.includes(input)
  }

  return {
    user,
    notDisable,
    isSearching: isLoading,
    teachers,
    teacherFilter
  }
}
